import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Modal, Form, Input, Select, InputNumber, Upload, message, Row, Col, Tag, Image, Typography, Tooltip, Badge, Dropdown, Menu as AntMenu, Switch, DatePicker, Statistic } from 'antd';
import { MENU_COLUMNS } from '../shared/table/columns';
import BaseTable from '../shared/table/BaseTable';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, UploadOutlined, SearchOutlined, FilterOutlined, MoreOutlined, ShoppingOutlined, DollarOutlined, StarOutlined, FireOutlined, ReloadOutlined, ExportOutlined, ImportOutlined, DownloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES, t } from '../utils/i18n';
import { ApiWrapper, InputValidator, ErrorHandler } from '../patches/error-handling-wrapper';
import { menuAPI, authAPI } from '../utils/api';
import { postJSON } from '../utils/api';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

// 创建API包装器实例
const apiWrapper = new ApiWrapper(null, { enableRetry: true, enableLogging: true });

const MenuPage = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(!!localStorage.getItem('admin_token'));
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [loginLoading, setLoginLoading] = useState(false);
  
  const handleLogin = async () => {
    setLoginLoading(true);
    try {
      console.log('登录表单数据:', loginForm);
      const response = await authAPI.login(loginForm);
      console.log('登录响应:', response);
      
      if (response.data && response.data.data && response.data.data.token) {
        const { token } = response.data.data;
        localStorage.setItem('admin_token', token);
        message.success('登录成功');
        setIsLoggedIn(true);
      } else {
        message.error(response.data?.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error(error.response?.data?.message || '登录时发生错误');
    } finally {
      setLoginLoading(false);
    }
  };
  
  const handleLogout = () => {
    localStorage.removeItem('admin_token');
    setIsLoggedIn(false);
    message.success('已退出登录');
  };
  
  const [menuItems, setMenuItems] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 组件加载时获取数据
  useEffect(() => {
    const fetchMenuItems = async () => {
      try {
        setLoading(true);
        const response = await menuAPI.getMenuItems();
        console.log('菜单API响应:', response);
        
        if (response.data && response.data.success && response.data.data && response.data.data.items) {
          setMenuItems(response.data.data.items);
          console.log('菜单数据已更新:', response.data.data.items);
        } else {
          console.warn('菜单API响应格式异常:', response);
          setMenuItems([]);
        }
      } catch (error) {
        console.error('获取菜单数据失败:', error);
        message.error('获取菜单数据失败');
        setMenuItems([]);
      } finally {
        setLoading(false);
      }
    };
    
    const fetchCategories = async () => {
      try {
        const response = await fetch('/api/menu/categories', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('分类API响应:', data);
          const categoryData = data.data || [];
          // 转换为前端需要的格式
          const formattedCategories = categoryData.map(cat => ({
            value: cat.name,
            label: cat.name,
            color: cat.color || '#1890ff'
          }));
          setCategories(formattedCategories);
          console.log('分类数据已更新:', formattedCategories);
        } else {
          console.error('获取分类数据失败:', response.status, response.statusText);
        }
      } catch (error) {
        console.error('获取分类数据失败:', error);
      }
    };
    
    if (isLoggedIn) {
      fetchMenuItems();
      fetchCategories();
    }
  }, [isLoggedIn]);
  
  // 现在使用API获取真实数据，不再需要静态示例数据

  const [categories, setCategories] = useState([]);

  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [templateLoading, setTemplateLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [dateRange, setDateRange] = useState(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [stats, setStats] = useState({
    totalItems: 0,
    availableItems: 0,
    hotItems: 0,
    totalSales: 0
  });

  // 计算过滤后的数据
  const filteredData = menuItems.filter(item => {
    // 搜索文本过滤
    if (searchText && !item.name.toLowerCase().includes(searchText.toLowerCase()) && 
        !item.description.toLowerCase().includes(searchText.toLowerCase()) ) {
      return false;
    }
    
    // 分类过滤
    if (categoryFilter !== 'all' && item.category !== categoryFilter) {
      return false;
    }
    
    // 状态过滤
    if (statusFilter !== 'all' && item.status !== statusFilter) {
      return false;
    }
    
    // 日期范围过滤
    if (dateRange && dateRange.length === 2) {
      const itemDate = dayjs(item.createTime);
      if (itemDate.isBefore(dateRange[0]) || itemDate.isAfter(dateRange[1])) {
        return false;
      }
    }
    
    return true;
  });

  useEffect(() => {
    calculateStats();
  }, [menuItems]);

  const calculateStats = () => {
    const totalItems = menuItems.length;
    const availableItems = menuItems.filter(item => item.status === 'available').length;
    const hotItems = menuItems.filter(item => item.isHot).length;
    const totalSales = menuItems.reduce((sum, item) => sum + item.sales, 0);

    setStats({
      totalItems,
      availableItems,
      hotItems,
      totalSales
    });
  };

  const getStatusColor = (status) => {
    const colors = {
      available: 'success',
      unavailable: 'error',
      hidden: 'warning'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      available: '可售',
      unavailable: '缺货',
      hidden: '隐藏'
    };
    return texts[status] || status;
  };

  const getCategoryColor = (category) => {
    const categoryObj = categories.find(cat => cat.value === category);
    return categoryObj ? categoryObj.color : '#666';
  };

  const handleEdit = (item) => {
    setEditingItem(item);
    form.setFieldsValue({
      name: item.name,
      category: item.category,
      price: item.price,
      originalPrice: item.originalPrice,
      description: item.description,
      ingredients: item.ingredients,
      status: item.status,
      isHot: item.isHot,
      isNew: item.isNew,
      stock: item.stock
    });
    setModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个菜品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setMenuItems(menuItems.filter(item => item.id !== id));
        message.success('删除成功');
      }
    });
  };

  const handleDownloadTemplate = async () => {
    try {
      setTemplateLoading(true);
      message.loading('正在准备下载模板...', 0);
      
      console.log('下载模板按钮已点击');
      addImportLog('template_click', '下载模板按钮已点击');
      
      const response = await menuAPI.downloadTemplate();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单导入模板_${dayjs().format('YYYY-MM-DD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('模板下载成功');
    } catch (error) {
      console.error('下载模板失败:', error);
      addImportLog('template_error', '下载模板失败', error);
      message.destroy();
      message.error('下载模板失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setTemplateLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      message.loading('正在准备导出...', 0);
      
      console.log('导出按钮已点击');
      
      // 使用V2三表结构API导出
      const response = await menuAPI.exportMenu();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单数据_${dayjs().format('YYYY-MM-DD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.destroy();
      message.error('导出失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setExportLoading(false);
    }
  };

  // 添加导入调试日志功能
  const [importLogs, setImportLogs] = useState([]);
  
  // 检查URL参数是否启用导入调试
  const isImportDebugEnabled = () => {
    if (typeof window === 'undefined') return false;
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('importDebug') === '1';
  };
  
  // 添加导入日志
  const addImportLog = (type, message, data = null) => {
    if (!isImportDebugEnabled()) return;
    
    const logEntry = {
      timestamp: new Date().toISOString(),
      type,
      message,
      data
    };
    
    console.log(`[menu-import-debug] ${type}:`, message, data);
    setImportLogs(prev => [...prev, logEntry]);
    
    // 同时保存到window对象，方便导出
    if (typeof window !== 'undefined') {
      window.__menuImportLogs = window.__menuImportLogs || [];
      window.__menuImportLogs.push(logEntry);
    }
  };
  
  // 导出日志功能
  const exportImportLogs = () => {
    if (!window.__menuImportLogs || window.__menuImportLogs.length === 0) {
      message.info('没有可导出的导入日志');
      return;
    }
    
    const logText = JSON.stringify(window.__menuImportLogs, null, 2);
    const blob = new Blob([logText], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `menu_import_logs_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success('导入日志已导出');
  };

  // 添加文件选择事件监听
  document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('cmbr:import:chosen', e => console.log('CHOSEN', e.detail?.name));
  });

  // V2三表结构导入功能
  const handleImport = () => {
    console.log('导入按钮已点击');
    addImportLog('click', '导入按钮已点击');
    message.info({ key: 'menu-import-select', content: '请选择要导入的Excel文件' });
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    input.style.display = 'none';
    document.body.appendChild(input);
    
    const cleanup = () => {
      try { document.body.removeChild(input); } catch {}
    };
  
    input.addEventListener('change', async (e) => {
      const file = e.target.files && e.target.files[0];
      if (!file) { cleanup(); return; }
      
      // 触发文件选择事件
      document.dispatchEvent(new CustomEvent('cmbr:import:chosen', { detail: { name: file.name } }));
      
      console.log('[IMPORT] start', Date.now());
      
      try {
        setImportLoading(true);
        
        console.log('开始导入V2三表结构Excel');
        addImportLog('upload_start', '开始上传文件', { filename: file.name, size: file.size });
        
        // 使用V2三表结构API导入
        const hide = message.loading('正在上传并触发验证...', 0);
        try {
          const validateResponse = await menuAPI.validateMenu(file);
          addImportLog('validate_response', '收到验证响应', validateResponse.data);
          
          const { job_id, validation_result } = validateResponse.data || {};
          if (!job_id) {
            hide();
            message.error('验证失败：未返回任务ID');
            addImportLog('error', '验证失败：未返回任务ID');
            return;
          }
  
          // 若立即返回验证失败，则直接下载错误报告
          if (validation_result && validation_result.success === false) {
            hide();
            message.error('验证失败：' + (validation_result.message || '格式错误'));
            addImportLog('validation_failed', '验证立即失败', validation_result);
            
            try {
              const errorResponse = await menuAPI.downloadErrors(job_id);
              const url = window.URL.createObjectURL(new Blob([errorResponse.data]));
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `导入错误报告_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            } catch (errorDownloadError) {
              console.error('下载错误报告失败:', errorDownloadError);
              addImportLog('error_download_failed', '下载错误报告失败', errorDownloadError);
            }
            return;
          }
          
          // 轮询任务状态
          hide();
          message.loading({ content: '正在验证数据...', key: 'menu-import-validate', duration: 0 });
          
          const start = Date.now();
          const timeoutMs = 60000; // 60秒超时
          const pollIntervalMs = 1500; // 1.5秒轮询一次
          
          let job = { status: 'uploaded' };
          let attempts = 0;
          const maxAttempts = 40; // 最多轮询40次
          
          while (job.status === 'uploaded' || job.status === 'validating') {
            if (attempts >= maxAttempts) {
              addImportLog('polling_max_attempts', '达到最大轮询次数', { attempts });
              break;
            }
            
            // 处理超时情况
            if (Date.now() - start >= timeoutMs) {
              addImportLog('timeout', '校验超时', { elapsed_ms: Date.now() - start });
              message.destroy('menu-import-validate');
              Modal.warning({
                title: '校验超时',
                content: '校验操作超时，请在导入中心查看结果',
                onOk: () => {
                  // 跳转到导入中心页面
                  window.location.href = '/import-center';
                }
              });
              return;
            }
            
            // 等待一段时间再轮询
            await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
            
            try {
              console.log(`轮询任务状态 (${attempts + 1}/${maxAttempts})...`);
              addImportLog('polling', `轮询任务状态 (${attempts + 1}/${maxAttempts})`, { job_id });
              
              const statusResponse = await menuAPI.getJobStatus(job_id);
              job = statusResponse.data;
              addImportLog('polling_response', '轮询响应', job);
              
              attempts++;
            } catch (pollError) {
              console.error('轮询任务状态失败:', pollError);
              addImportLog('polling_error', '轮询任务状态失败', pollError);
              message.destroy('menu-import-validate');
              message.error('获取任务状态失败，请稍后重试');
              return;
            }
          }
          
          message.destroy('menu-import-validate');
          
          // 处理验证完成的情况
          if (job.status === 'validated') {
            console.log('验证成功，准备提交导入');
            addImportLog('validation_success', '验证成功，准备提交导入', job);
            
            try {
              // 自动提交导入，不需要用户确认
              const autoCommit = async () => {
                    const loadingKey = 'menu-import-commit';
                    try {
                      message.loading({ content: '正在导入数据...', key: loadingKey, duration: 0 });
                      console.log('提交导入，任务ID:', job.job_id || job_id);
                      addImportLog('commit_start', '开始提交导入', { job_id: job.job_id || job_id });
                      
                      // 确保使用正确的任务ID
                      const taskId = job.job_id || job_id;
                      if (!taskId) {
                        message.error({ key: 'menu-import-commit-error', content: '提交失败: 无效的任务ID' });
                        addImportLog('error', '提交失败: 无效的任务ID');
                        return;
                      }
                      
                      try {
                        // 添加超时处理
                        // 处理超时情况
                        if (Date.now() - start >= timeoutMs) {
                          addImportLog('timeout', '校验超时', { elapsed_ms: Date.now() - start });
                          Modal.warning({
                            title: '校验超时',
                            content: '校验操作超时，请在导入中心查看结果',
                            onOk: () => {
                              // 跳转到导入中心页面
                              window.location.href = '/import-center';
                            }
                          });
                          return;
                        }
                        
                        // 使用menuAPI.commitImport函数提交导入
                        const commitResponse = await menuAPI.commitImport(taskId);
                        
                        addImportLog('commit_response', '提交导入响应', commitResponse.data);
                        
                        if (commitResponse.data && commitResponse.data.success) {
                          message.success({ key: loadingKey, content: '导入成功' });
                          addImportLog('commit_success', '导入成功', commitResponse.data);
                          
                          // 强制刷新菜单数据
                          setTimeout(async () => {
                            try {
                              const response = await menuAPI.getMenuItems({ _t: Date.now() });
                              if (response.data && response.data.success && response.data.data && response.data.data.items) {
                                setMenuItems(response.data.data.items);
                                message.success(`数据已更新，共 ${response.data.data.items.length} 条菜品`);
                              } else {
                                window.location.reload();
                              }
                            } catch (error) {
                              console.error('刷新数据失败:', error);
                              window.location.reload();
                            }
                          }, 2000);
                        } else {
                          message.error({ 
                            key: loadingKey, 
                            content: '导入失败: ' + (commitResponse.data?.message || '未知错误') 
                          });
                          addImportLog('commit_failed', '导入失败', commitResponse.data);
                        }
                      } catch (timeoutError) {
                        message.destroy(loadingKey);
                        console.error('提交导入超时或失败:', timeoutError);
                        addImportLog('commit_timeout', '提交导入超时或失败', timeoutError);
                        message.error({ key: 'menu-import-timeout', content: '提交导入超时或失败，请稍后重试' });
                      }
                    } catch (commitError) {
                      console.error('提交导入失败:', commitError);
                      addImportLog('commit_error', '提交导入失败', commitError);
                      message.error({ key: 'menu-import-commit-error', content: '导入失败: ' + (commitError.response?.data?.message || commitError.message) });
                    }
              };
              
              // 立即执行自动提交
              await autoCommit();
            } catch (modalError) {
              console.error('显示确认对话框失败:', modalError);
              addImportLog('modal_error', '显示确认对话框失败', modalError);
              message.error({ key: 'menu-import-modal-error', content: '显示确认对话框失败，请重试' });
            }
          } else {
            // 校验失败或存在错误报告
            console.log('验证失败，状态:', job.status);
            addImportLog('validation_failed', '验证失败', { status: job.status, job });
            
            message.error('验证失败，请查看错误报告');
            
            try {
              const errorResponse = await menuAPI.downloadErrors(job_id);
              const url = window.URL.createObjectURL(new Blob([errorResponse.data]));
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `导入错误报告_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            } catch (errorDownloadError) {
              console.error('下载错误报告失败:', errorDownloadError);
              addImportLog('error_download_failed', '下载错误报告失败', errorDownloadError);
            }
          }
        } catch (validateError) {
          hide();
          console.error('验证过程出错:', validateError);
          addImportLog('validation_error', '验证过程出错', validateError);
          message.error('验证过程出错: ' + (validateError.response?.data?.message || validateError.message));
          return;
        }
      } catch (error) {
        console.error('导入失败:', error);
        addImportLog('error', '导入失败', error);
        message.error({ key: 'menu-import-error', content: '导入失败: ' + (error.response?.data?.message || error.message) });
      } finally {
        setImportLoading(false);
        cleanup();
      }
    });
  
    // 在下一个事件循环触发点击，提升兼容性（Safari等）
    setTimeout(() => input.click(), 0);
  };

  // 重新获取菜品数据的函数
  const refreshMenuItems = async () => {
    try {
      setLoading(true);
      const response = await menuAPI.getMenuItems();
      console.log('刷新菜单API响应:', response);
      
      if (response.data && response.data.success && response.data.data && response.data.data.items) {
        setMenuItems(response.data.data.items);
        console.log('菜单数据已刷新:', response.data.data.items);
      } else {
        console.warn('刷新菜单API响应格式异常:', response);
      }
    } catch (error) {
      console.error('刷新菜单数据失败:', error);
      message.error('刷新菜单数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      if (editingItem) {
        // 编辑菜品 - 调用API保存到后台
        const response = await menuAPI.updateMenuItem(editingItem.id, values);
        if (response.data && response.data.success) {
          message.success('菜品信息更新成功');
          // 重新获取最新数据
          await refreshMenuItems();
        } else {
          message.error(response.data?.message || '更新失败');
          return;
        }
      } else {
        // 新增菜品 - 调用API保存到后台
        const response = await menuAPI.createMenuItem(values);
        if (response.data && response.data.success) {
          message.success('菜品添加成功');
          // 重新获取最新数据
          await refreshMenuItems();
        } else {
          message.error(response.data?.message || '添加失败');
          return;
        }
      }
      
      setModalVisible(false);
      setEditingItem(null);
      form.resetFields();
    } catch (error) {
      console.error('保存失败:', error);
      message.error(getErrorMessage(PAGES.MENU, ERROR_TYPES.SAVE_FAILED));
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (itemId, newStatus) => {
    try {
      // 调用API更新状态到后台
      const statusData = { is_available: newStatus === 'available' };
      const response = await menuAPI.updateAvailability(itemId, statusData);
      
      if (response.data && response.data.success) {
        message.success('状态更新成功');
        // 重新获取最新数据
        await refreshMenuItems();
      } else {
        message.error(response.data?.message || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
    }
  };

  const handleToggleHot = async (itemId) => {
    try {
      const item = menuItems.find(item => item.id === itemId);
      if (!item) return;
      
      // 调用API更新热门状态到后台
      const response = await menuAPI.updateMenuItem(itemId, { isHot: !item.isHot });
      
      if (response.data && response.data.success) {
        message.success('热门状态已更新');
        // 重新获取最新数据
        await refreshMenuItems();
      } else {
        message.error(response.data?.message || '热门状态更新失败');
      }
    } catch (error) {
      console.error('热门状态更新失败:', error);
      message.error('热门状态更新失败，请重试');
    }
  };

  // 快捷日期选择函数
  const handleQuickDateSelect = (days) => {
    const endDate = dayjs();
    const startDate = dayjs().subtract(days, 'day');
    setDateRange([startDate, endDate]);
  };

  const clearDateFilter = () => {
    setDateRange(null);
  };

  const filteredItems = menuItems.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.description.toLowerCase().includes(searchText.toLowerCase());
    const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;
    const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
    
    let matchesDate = true;
    if (dateRange && dateRange.length === 2) {
      const itemDate = dayjs(item.updateTime);
      matchesDate = itemDate.isAfter(dateRange[0].startOf('day')) && itemDate.isBefore(dateRange[1].endOf('day'));
    }
    
    return matchesSearch && matchesCategory && matchesStatus && matchesDate;
  });

  const getActionMenu = (item) => (
    <AntMenu>
      <AntMenu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEdit(item)}>
        编辑菜品
      </AntMenu.Item>
      <AntMenu.Item key="available" onClick={() => handleStatusChange(item.id, 'available')}>
        设为可售
      </AntMenu.Item>
      <AntMenu.Item key="unavailable" onClick={() => handleStatusChange(item.id, 'unavailable')}>
        设为缺货
      </AntMenu.Item>
      <AntMenu.Item key="hidden" onClick={() => handleStatusChange(item.id, 'hidden')}>
        隐藏菜品
      </AntMenu.Item>
      <AntMenu.Item key="hot" onClick={() => handleToggleHot(item.id)}>
        {item.isHot ? '取消热门' : '设为热门'}
      </AntMenu.Item>
      <AntMenu.Divider />
      <AntMenu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDelete(item.id)}>
        删除菜品
      </AntMenu.Item>
    </AntMenu>
  );

  // 基于统一列配置生成实际渲染列
  const columns = MENU_COLUMNS.map(column => {
    if (column.key === 'id') {
      return {
        ...column,
        render: (id, item) => (
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{ fontWeight: 500, color: '#666' }}>{id}</span>
            <Image
              width={32}
              height={32}
              src={item.image || '/images/menu-placeholder.svg'}
              style={{ borderRadius: '4px', objectFit: 'cover' }}
              preview={{
                visible: false,
                onVisibleChange: (visible) => {
                  if (visible) {
                    setPreviewImage(item.image || '/images/menu-placeholder.svg');
                    setPreviewVisible(true);
                  }
                }
              }}
            />
          </div>
        )
      };
    }
    if (column.key === 'image') {
      return {
        ...column,
        render: (_, item) => (
          <div style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
            <Image
              width={48}
              height={48}
              src={item.image || '/images/menu-placeholder.svg'}
              style={{ borderRadius: '6px', objectFit: 'cover' }}
              preview={{
                visible: false,
                onVisibleChange: (visible) => {
                  if (visible) {
                    setPreviewImage(item.image || '/images/menu-placeholder.svg');
                    setPreviewVisible(true);
                  }
                }
              }}
            />
            {item.isHot && (
              <Badge 
                count={<FireOutlined style={{ color: '#f5222d', fontSize: '10px' }} />} 
                style={{ position: 'absolute', top: -2, right: -2 }}
                size="small"
              />
            )}
          </div>
        )
      };
    }
    if (column.key === 'name') {
      return {
        ...column,
        render: (name, item) => (
          <div>
            <div style={{ fontWeight: 600, fontSize: '14px', marginBottom: '2px' }}>
              {name}
            </div>
            {item.isNew && (
              <Badge count="新" size="small" style={{ backgroundColor: '#52c41a', fontSize: '10px' }} />
            )}
          </div>
        )
      };
    }
    if (column.key === 'description') {
      return {
        ...column,
        render: (description) => (
          <div style={{ 
            color: '#666', 
            fontSize: '12px',
            lineHeight: '1.4',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}>
            {description}
          </div>
        )
      };
    }
    if (column.key === 'ingredients') {
      return {
        ...column,
        render: (ingredients) => (
          <div style={{ 
            color: '#666', 
            fontSize: '12px',
            lineHeight: '1.4',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}>
            {ingredients || '暂无配料信息'}
          </div>
        )
      };
    }
    if (column.key === 'price') {
      return {
        ...column,
        render: (_, item) => (
          <div>
            <div style={{ fontWeight: 600, color: '#f5222d', fontSize: '14px' }}>
              S${item.price}
            </div>
            {item.originalPrice > item.price && (
              <div style={{ color: '#999', fontSize: '11px', textDecoration: 'line-through' }}>
                S${item.originalPrice}
              </div>
            )}
          </div>
        )
      };
    }
    if (column.key === 'category') {
      return {
        ...column,
        render: (category) => (
          <Tag color={getCategoryColor(category)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {category}
          </Tag>
        )
      };
    }
    if (column.key === 'status') {
      return {
        ...column,
        render: (status) => (
          <Tag color={getStatusColor(status)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {getStatusText(status)}
          </Tag>
        )
      };
    }
    if (column.key === 'stock') {
      return {
        ...column,
        render: (stock) => (
          <div style={{ 
            color: stock > 10 ? '#52c41a' : stock > 0 ? '#faad14' : '#f5222d',
            fontWeight: 600,
            fontSize: '13px',
            textAlign: 'center'
          }}>
            {stock}
          </div>
        )
      };
    }
    if (column.key === 'rating') {
      return {
        ...column,
        render: (rating) => (
          <div style={{ display: 'flex', alignItems: 'center', gap: '2px', justifyContent: 'center' }}>
            <StarOutlined style={{ color: '#faad14', fontSize: '11px' }} />
            <span style={{ fontSize: '12px' }}>{rating}</span>
          </div>
        )
      };
    }
    if (column.key === 'actions') {
      return {
        ...column,
        render: (_, item) => (
          <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
            <Tooltip title="编辑">
              <Button 
                type="primary" 
                size="small" 
                icon={<EditOutlined />}
                onClick={() => handleEdit(item)}
              />
            </Tooltip>
            <Dropdown overlay={getActionMenu(item)} trigger={['click']}>
              <Button size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </div>
        )
      };
    }
    return column;
  });

  const uploadProps = {
    name: 'image',
    action: editingItem?.id ? `/api/admin/menu/items/${editingItem.id}/image` : null,
    maxCount: 1,
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('admin_token') || localStorage.getItem('token')}`,
    },
    beforeUpload: (file) => {
      // 检查文件类型
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      if (!isImage) {
        message.error('只能上传 JPEG、PNG、WebP 格式的图片!');
        return false;
      }
      // 检查文件大小 (5MB)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      // 如果没有选择菜品，不允许上传
      if (!editingItem?.id) {
        message.error('请先保存菜品信息后再上传图片!');
        return false;
      }
      return true;
    },
    onChange(info) {
      if (info.file.status === 'uploading') {
        message.loading(`正在上传 ${info.file.name}...`, 0);
      } else if (info.file.status === 'done') {
        message.destroy();
        message.success(`${info.file.name} 上传成功!`);
        // 刷新菜品列表以显示新图片
        fetchMenuItems();
      } else if (info.file.status === 'error') {
        message.destroy();
        message.error(`${info.file.name} 上传失败: ${info.file.response?.message || '未知错误'}`);
      }
    },
    disabled: !editingItem?.id,
  };

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ 
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '16px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{ 
            background: 'rgba(255,255,255,0.2)',
            borderRadius: '12px',
            padding: '12px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <ShoppingOutlined style={{ fontSize: '32px', color: '#fff' }} />
          </div>
          <div>
            <Title level={2} style={{ margin: 0, color: '#fff' }}>
              菜单管理
            </Title>
            <p style={{ margin: '8px 0 0 0', color: 'rgba(255,255,255,0.8)', fontSize: '16px' }}>
              管理餐厅菜品信息、价格和库存状态
            </p>
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>菜品总数</span>}
              value={stats.totalItems}
              prefix={<ShoppingOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>可售菜品</span>}
              value={stats.availableItems}
              prefix={<ShoppingOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>热门菜品</span>}
              value={stats.hotItems}
              prefix={<FireOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>总销量</span>}
              value={stats.totalSales}
              prefix={<DollarOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 登录表单 */}
      {!isLoggedIn ? (
        <Card
          title={<Title level={4} style={{ margin: 0, color: '#1a1a1a' }}>管理员登录</Title>}
          style={{
            borderRadius: '16px',
            boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
            border: 'none',
            overflow: 'hidden',
            marginBottom: '20px'
          }}
        >
          <Form layout="vertical">
            <Form.Item label="邮箱" required>
              <Input 
                placeholder="请输入邮箱" 
                value={loginForm.email} 
                onChange={(e) => setLoginForm({...loginForm, email: e.target.value})}
              />
            </Form.Item>
            <Form.Item label="密码" required>
              <Input.Password 
                placeholder="请输入密码" 
                value={loginForm.password} 
                onChange={(e) => setLoginForm({...loginForm, password: e.target.value})}
              />
            </Form.Item>
            <Form.Item>
              <Button 
                type="primary" 
                onClick={handleLogin} 
                loading={loginLoading}
                style={{ width: '100%' }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      ) : (
        <Card
          style={{
            borderRadius: '16px',
            boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
            border: 'none',
            overflow: 'hidden',
            marginBottom: '20px'
          }}
        >
          <Space>
            <span>已登录</span>
            <Button onClick={handleLogout}>退出登录</Button>
          </Space>
        </Card>
      )}
      
      {/* 菜品列表 */}
      <Card 
        title={<Title level={4} style={{ margin: 0, color: '#1a1a1a' }}>菜品列表</Title>}
        style={{
          borderRadius: '16px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
          border: 'none',
          overflow: 'hidden'
        }}
        extra={
          <Space>
            <Button 
              icon={<DownloadOutlined />} 
              style={{ borderRadius: '8px' }}
              onClick={handleDownloadTemplate}
              loading={templateLoading}
              disabled={!isLoggedIn}
            >
              下载模板
            </Button>
            <Button 
              icon={<ImportOutlined />} 
              style={{ borderRadius: '8px' }}
              onClick={handleImport}
              loading={importLoading}
              disabled={!isLoggedIn}
            >
              导入
            </Button>
            <Button 
              icon={<ExportOutlined />} 
              style={{ borderRadius: '8px' }}
              onClick={handleExport}
              loading={exportLoading}
              disabled={!isLoggedIn}
            >
              导出
            </Button>
            <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} style={{ borderRadius: '8px' }}>刷新</Button>
            {isImportDebugEnabled() && (
              <Button 
                type="dashed"
                icon={<DownloadOutlined />}
                onClick={exportImportLogs}
                style={{ borderRadius: '8px' }}
              >
                导出日志
              </Button>
            )}
            <Button 
              icon={<ReloadOutlined />}
              onClick={refreshMenuItems}
              style={{ borderRadius: '8px' }}
              disabled={!isLoggedIn}
              loading={loading}
            >
              刷新数据
            </Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingItem(null);
                form.resetFields();
                setModalVisible(true);
              }}
              style={{ 
                borderRadius: '8px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)'
              }}
              disabled={!isLoggedIn}
            >
              添加菜品
            </Button>
          </Space>
        }
      >
        {/* 筛选器 */}
        <div style={{ 
          marginBottom: '20px', 
          padding: '16px',
          background: '#fafafa',
          borderRadius: '12px',
          display: 'flex', 
          gap: '12px', 
          flexWrap: 'wrap',
          alignItems: 'center'
        }}>
          <Input.Search
            placeholder="搜索菜品名称或描述"
            style={{ 
              width: 300,
              borderRadius: '8px'
            }}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            prefix={<SearchOutlined />}
          />
          <Select
            placeholder="分类筛选"
            style={{ 
              width: 120,
              borderRadius: '8px'
            }}
            value={categoryFilter}
            onChange={setCategoryFilter}
          >
            <Option value="all">全部分类</Option>
            {categories.map(cat => (
              <Option key={cat.value} value={cat.value}>{cat.label}</Option>
            ))}
          </Select>
          <Select
            placeholder="状态筛选"
            style={{ 
              width: 120,
              borderRadius: '8px'
            }}
            value={statusFilter}
            onChange={setStatusFilter}
          >
            <Option value="all">全部状态</Option>
            <Option value="available">可售</Option>
            <Option value="unavailable">缺货</Option>
            <Option value="hidden">隐藏</Option>
          </Select>
        </div>
        
        {/* 日期筛选器 */}
        <div style={{ 
          marginBottom: '20px', 
          padding: '16px',
          background: '#fafafa',
          borderRadius: '12px',
          display: 'flex', 
          alignItems: 'center', 
          gap: '12px', 
          flexWrap: 'wrap' 
        }}>
          <span style={{ fontWeight: '500', color: '#666', fontSize: '14px' }}>日期筛选：</span>
          <RangePicker
            value={dateRange}
            onChange={setDateRange}
            placeholder={['开始日期', '结束日期']}
            style={{ 
              width: '280px',
              borderRadius: '8px'
            }}
            format="YYYY-MM-DD"
          />
          <div style={{ display: 'flex', gap: '8px' }}>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(7)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 7 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              过去一周
            </Button>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(30)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 30 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              1个月
            </Button>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(90)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 90 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              3个月
            </Button>
            <Button 
              size="small" 
              onClick={clearDateFilter}
              style={{ borderRadius: '6px' }}
            >
              清除
            </Button>
          </div>
        </div>

        <BaseTable
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: filteredData.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }
          }}
          loading={loading}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              disabled: record.status === 'deleted'
            })
          }}
        />
      </Card>

      {/* 编辑/添加菜品模态框 */}
      <Modal
        title={editingItem ? t('editDish') : t('addDish')}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false);
          setEditingItem(null);
          form.resetFields();
        }}
        confirmLoading={loading}
        width={800}
        okText={t('save')}
        cancelText={t('cancel')}
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: '20px' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label={t('dishName')}
                rules={[{ required: true, message: t('enterDishName') }]}
              >
                <Input placeholder={t('enterDishName')} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label={t('category')}
                rules={[{ required: true, message: t('selectCategory') }]}
              >
                <Select placeholder={t('selectCategory')}>
                  {categories.map(cat => (
                    <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label={t('price')}
                rules={[{ required: true, message: t('enterPrice') }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={t('enterPrice')}
                  min={0}
                  precision={2}
                  addonBefore="S$"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="originalPrice"
                label={t('originalPrice')}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={t('enterOriginalPrice')}
                  min={0}
                  precision={2}
                  addonBefore="S$"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="stock"
                label={t('stock')}
                rules={[{ required: true, message: t('enterStock') }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={t('enterStock')}
                  min={0}
                />
              </Form.Item>
            </Col>

          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="description"
                label={t('description')}
                rules={[{ required: true, message: t('enterDescription') }]}
              >
                <TextArea rows={3} placeholder={t('enterDescription')} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="ingredients"
                label={t('ingredients')}
              >
                <TextArea rows={3} placeholder={t('enterIngredients')} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="isHot"
                label="热门菜品"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="isNew"
                label="新品推荐"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="image"
                label="菜品图片"
              >
                <Upload {...uploadProps}>
                  <Button icon={<UploadOutlined />} size="small">上传图片</Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 图片预览 */}
      <Modal
        open={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default MenuPage;